package com.secsbrain.development.biz.impl;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSON;
import com.secsbrain.deploy.client.iface.DeployService;
import com.secsbrain.development.biz.constant.EnumDefinition;
import com.secsbrain.frame.lock.Callback;
import com.secsbrain.frame.lock.DistributedLockTemplate;
import com.secsbrain.development.biz.IDeployPlanRecordService;
import com.secsbrain.development.biz.IDeployPlanService;
import com.secsbrain.development.biz.IDeployPlanTestService;
import com.secsbrain.development.biz.IProjectAppService;
import com.secsbrain.development.dal.mapper.DeployPlanTestMapper;
import com.secsbrain.development.dal.model.DeployPlan;
import com.secsbrain.development.dal.model.DeployPlanRecord;
import com.secsbrain.development.dal.model.DeployPlanTest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.secsbrain.common.ResponseVo;
import com.secsbrain.common.utils.DevOpsHttpUtils;
import com.secsbrain.deploy.client.constant.EnumDefinition.BuildStatus;
import com.secsbrain.deploy.client.model.BuildRecord;
import com.baomidou.framework.service.impl.SuperServiceImpl;
import com.baomidou.mybatisplus.plugins.Page;

/**
 *
 * DeployPlanTest 表数据服务层接口实现类
 *
 */
@Service
public class DeployPlanTestServiceImpl extends SuperServiceImpl<DeployPlanTestMapper, DeployPlanTest> implements IDeployPlanTestService {
	
    private static final Logger logger = LoggerFactory.getLogger(DeployPlanTestServiceImpl.class);
	
	@Autowired
	DeployService deployService;
	
	@Autowired
    IDeployPlanService deployPlanService;
	
    @Autowired
    IDeployPlanRecordService deployPlanRecordService;
	
	@Autowired
    IProjectAppService projectAppService;
	
	@Autowired
	DistributedLockTemplate distributedLockTemplate;
	
	@Autowired
	DevOpsHttpUtils httpUtils;
	
	@Value("${secsbrain.qa.url}")
    private String secsbrainQaUrl;
	 
	/* (non-Javadoc)
	 * @see IDeployPlanTestService#handleAutoTest(DeployPlanTest)
	 */
	@SuppressWarnings("rawtypes")
	@Override
	public void handleAutoTest(DeployPlanTest deployPlanTest) {
		//先查询发布计划的应用是否都发布好，如果有失败的，则执行更新为不执行测试
		DeployPlanRecord deployPlanRecordParam=new DeployPlanRecord();
		deployPlanRecordParam.setPlanId(deployPlanTest.getPlanId());
		Page<DeployPlanRecord> page=new Page<DeployPlanRecord>(1, 1);
		Page<DeployPlanRecord> pageList=deployPlanRecordService.selectPage(page, deployPlanRecordParam, " create_time desc");
		if(pageList.getTotal()<=0){
			logger.warn("没有找到发布计划的发布记录！");
			return;
		}
		DeployPlanRecord deployPlanRecord=pageList.getRecords().get(0);
		ResponseVo<List<BuildRecord>> batchBuildRecordVo=deployService.queryBuildListByBatchId(deployPlanRecord.getId(),"test");
		if(!batchBuildRecordVo.isSuccess()){
			logger.error("查询批量构建记录失败："+batchBuildRecordVo.getMsg());
			return;
		}
		
		List<BuildRecord> buildRecordList=batchBuildRecordVo.getData();
		boolean failFlag=false;
		for(BuildRecord buildRecord:buildRecordList){
			if(BuildStatus.FAILUE.getCode().equals(buildRecord.getStatus())){
				failFlag=true;
				break;
			}
		}
		
		Date nowDate=new Date();

		//发布失败则不跑测试任务了
		if(failFlag){
			logger.debug("有发布失败的应用，不跑测试任务了");
			DeployPlanTest deployPlanTestUp=new DeployPlanTest();
			deployPlanTestUp.setId(deployPlanTest.getId());
			deployPlanTestUp.setStatus(EnumDefinition.TestStatus.NONE.getCode());
			deployPlanTestUp.setUpdateTime(nowDate);
			this.updateSelectiveById(deployPlanTestUp);
			return;
		}
		
		boolean passFlag=true;
		for(BuildRecord buildRecord:buildRecordList){
			if(!BuildStatus.SUCCESS.getCode().equals(buildRecord.getStatus())){
				passFlag=false;
				break;
			}
		}
		
		if(passFlag){
			logger.debug("调用自动化测试接口开始。。。");
			DeployPlan deployPlan=deployPlanService.selectById(deployPlanTest.getPlanId());
			
			Map<String, String> params=new HashMap<>();
			params.put("projectId", deployPlan.getProjectId());
			params.put("buildId", deployPlan.getBuildId());
			logger.debug("调用质量平台开始。。。params:{}",params);
			String resultData=httpUtils.submitPost(secsbrainQaUrl, null,params);
			logger.debug("质量平台返回结果:{}",resultData);

			boolean success=false;
			if(resultData!=null){
				try {
					Map map= JSON.parseObject(resultData, Map.class);
					if((Boolean) map.get("success")){
						success=true;
					}
				} catch (Exception e) {
				}
			}

			DeployPlanTest deployPlanTestUp=new DeployPlanTest();
			deployPlanTestUp.setId(deployPlanTest.getId());
			deployPlanTestUp.setStatus(success? EnumDefinition.TestStatus.ING.getCode(): EnumDefinition.TestStatus.FAIL.getCode());
			deployPlanTestUp.setUpdateTime(nowDate);
			
			IDeployPlanTestService deployPlanTestService=this;
			distributedLockTemplate.execute("update_deployPlanTest_"+deployPlanTest.getId(), 5000, new Callback() {

				@Override
				public Object onGetLock() throws InterruptedException {
					deployPlanTestService.updateSelectiveById(deployPlanTestUp);
					return null;
				}

				@Override
				public Object onTimeout() throws InterruptedException {
					return null;
				}
				
			});

		}
		
	}

}